<template>
  <div>
    <f-search :search="search" @search="changeSearch" v-model:initForm="searchForm"></f-search>
    <f-table :table-data="tableData" :tableColumn="tableColumn" :is-selection="true" :is-index="true" :pagination="pagination" @change="getPagination">
      <template #operation="props">
        <el-popconfirm width="220" confirm-button-text="确认" cancel-button-text="取消" :hide-icon="true" :hide-after="0" @confirm="handleDeleteArticle(props.row)" title="确认删除文章数据?">
          <template #reference>
            <el-button>删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </f-table>
  </div>
</template>

<script lang="ts" setup>
import { onMounted } from 'vue'

import FTable from '@/components/FTable.vue'
import FSearch from '@/components/FSearch.vue'
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import FUpload from '@/components/FUpload.vue'
import { articleList, deleteArticle } from '@/apis/article'
import { ElMessage } from 'element-plus'
import useDelete from '@/composables/useDelete.ts'

const router = useRouter()
const route = useRoute()

interface columnType {
  label: string
  prop: string
  slotName?: string
  render?: any
  sortable?: string
  showOverflowTooltip?: boolean
  width?: string
  fixed?: string
  align?: string

  [key: string]: any
}

const tableColumn = ref<columnType[]>([
  {
    label: '标题',
    prop: 'title',
  },
  {
    label: '内容',
    prop: 'content',
  },
  {
    label: '创建时间',
    prop: 'createdAt',
  },
])
onMounted(() => {
  getArticleList(true)
})
/**
 * 搜索
 * */
type searchType = {
  label?: string
  prop: string
  placeholder?: string
  require?: boolean
  type?: string
  [key: string]: any
}
const search = ref<searchType[]>([
  { label: '文章标题', prop: 'title', placeholder: '请输文章标题', required: true, type: 'input' },
  { label: '文章类容', prop: 'content', placeholder: '请输入文章类容', required: false, type: 'input' },
])
const searchForm = ref({
  title: '',
  content: '',
})
const changeSearch = async (e) => {
  searchForm.value = e
  console.log(searchForm.value)
  await getArticleList(true)
}
/**
 * 文章列表
 * */
const pagination = ref({
  total: 0,
  currentPage: 1,
  pageSize: 5,
})
const tableData = ref([])

async function getArticleList(init?: boolean) {
  if (init) pagination.value.currentPage = 1
  const params = {
    pageNo: pagination.value.currentPage,
    pageSize: pagination.value.pageSize,
    ...searchForm.value,
  }
  const res = await articleList(params)
  if (res.code !== 200) return
  pagination.value.total = res.data.total
  tableData.value = res.data.row
}

/**
 * 删除单条文章
 * */
const { calculatePageNumbers } = useDelete()
const handleDeleteArticle = async (row) => {
  const res = await deleteArticle(row.id)
  calculatePageNumbers(pagination)
  ElMessage.success('删除成功')
  await getArticleList()
}

/**
 * 分页查询
 * */
function getPagination() {
  getArticleList()
}
</script>

<style scoped lang="scss"></style>
